package com.da.auth.controller;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

/**
 * @Author: hyacinth
 * @CreateTime: 2025-01-31
 * @Version: 1.0
 */
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据键获取字符串类型的值
     *
     * @param key Redis 键
     * @return Redis 值
     */
    @GetMapping("/string/{key}")
    public String getString(@PathVariable String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 根据键获取Object类型的值
     *
     * @param key Redis 键
     * @return Redis 值
     */
    @GetMapping("/object/{key}")
    public Object getObject(@PathVariable String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 设置字符串类型的键值对
     *
     * @param key   Redis 键
     * @param value Redis 值
     * @return 操作结果
     */
    @PostMapping("/string/{key}")
    public String setString(@PathVariable String key, @RequestParam String value) {
        stringRedisTemplate.opsForValue().set(key, value);
        return "OK";
    }


    /**
     * 设置任意类型的键值对
     *
     * @param key   Redis 键
     * @param value Redis 值
     * @return 操作结果
     */
    @PostMapping("/object/{key}")
    public String setObject(@PathVariable String key, @RequestBody Object value) {
        redisTemplate.opsForValue().set(key, value);
        return "OK";
    }

    /**
     * 获取所有的键
     *
     * @return Redis 所有的键
     */
    @GetMapping("/keys")
    public Set<String> getKeys() {
        return redisTemplate.keys("*");
    }


    /**
     * 获取 Hash 所有键值对
     *
     * @param key Redis 键
     * @return Map<String, String>
     */
    @GetMapping("/hash/{key}")
    public Map<Object, Object> getHash(@PathVariable String key) {
        return redisTemplate.opsForHash().entries(key);
    }


    /**
     * 设置 Hash 的键值对
     *
     * @param key     Redis 键
     * @param hashKey Hash 键
     * @param value   Hash 值
     * @return 操作结果
     */
    @PostMapping("/hash/{key}")
    public String setHash(@PathVariable String key, @RequestParam String hashKey, @RequestParam String value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
        return "OK";
    }

    /**
     * 删除键
     *
     * @param key Redis 键
     * @return 操作结果
     */
    @DeleteMapping("/{key}")
    public String deleteKey(@PathVariable String key) {
        redisTemplate.delete(key);
        return "OK";
    }
}
